import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 导入登录注册组件
const Login = () => import('@/views/Login/Login.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')
const Reg = () => import('@/views/Reg/Reg.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    // 3. 开启路由重定向
    redirect: '/home',
    children: [
      // 2. home 作为 子路由规则
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      // 声明子路由规则
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }

]

const router = new VueRouter({
  routes
})
// 防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
/*  注册全局守卫:每次路由跳转前拦截决定是否放行,一旦注册必须调用  next()
    no 到哪里去
    form  哪里来
    next  是否放行
*/
router.beforeEach((to, from, next) => {
  // 需求:如果没有token  不允许除了登录注册以外的所有页面
  // 1.没有token
  // 2.进入的页面不是登录与注册
  if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
    Vue.prototype.$message.error('你还没有登录')
    return next('/login')
  }
  next()
})

export default router
